package com.goddess.yeecolor.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.goddess.yeecolor.R;
import com.goddess.yeecolor.base.BaseActivity;
import com.goddess.yeecolor.tools.JumpIntents;
import com.goddess.yeecolor.tools.LogUtils;
import com.goddess.yeecolor.tools.MyUrl;
import com.goddess.yeecolor.tools.OkttpUtils;
import com.goddess.yeecolor.tools.SharePreceUtils;
import com.goddess.yeecolor.tools.ToastUtils;
import com.goddess.yeecolor.view.CircleImageView;
import com.goddess.yeecolor.view.Titles;
import com.goddess.yeecolor.view.dialog_progress;
import com.mob.tools.utils.UIHandler;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 登录
 */
public class LoginAcitivity extends BaseActivity implements View.OnClickListener,PlatformActionListener,Handler.Callback{
    private String connect_third,connect_uuid;//第三方登录的typed uuid
    private int state;//判断第三方是否登录  注册等
    private ProgressDialog dialog;
    private String type,uuid;
    private LinearLayout login_normal,login_duanxin;//短信验证码布局
    private EditText login_phonenormal,login_psdnormal;//普通
    private EditText login_phone,login_psd;//短信验证
    private Button btn_enrollnormal,login_send,btn_enroll;
    private TextView login_type,login_typeduanxin;
    private CircleImageView qq,wx,sina;
    private View mView;
    private String TAGTYPE="账号密码登录";
    private Bundle bundle;
    private TimeCount time;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        mView= LayoutInflater.from(this).inflate(R.layout.activity_login,null);
        setContentView(mView);
        ShareSDK.initSDK(this);//初始化
        initFindView();
        initOnClck();

    }

    @Override
    public void initOnClck() {
        wx.setOnClickListener(this);
        qq.setOnClickListener(this);
        sina.setOnClickListener(this);
    }


    @Override
    public void initFindView() {
        time=new TimeCount(120*1000,1000);
        Titles.initBack(mView,R.mipmap.back,(view)->{
            SharePreceUtils.saveOne("type",1,"show");
            overridePendingTransition(0,0);
            finish();
        });
        Titles.initTitleRight2(mView, "注册", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initData();
                bundle=new Bundle();
                bundle.putString("Tag","普通");
                JumpIntents.startIntent(LoginAcitivity.this,RegisterActivity.class,bundle);
            }
        });
        qq= (CircleImageView) mView.findViewById(R.id.login_qq);
        wx= (CircleImageView) mView.findViewById(R.id.login_wx);
        sina= (CircleImageView) mView.findViewById(R.id.login_sina);
        isType();
    }

    @Override
    public void initData() {

    }

    private dialog_progress dialog_progress;
    private void setProgress(){
        dialog_progress=new dialog_progress(this);
        dialog_progress.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog_progress.setCanceledOnTouchOutside(false);//按返回键可以关闭进度条
        dialog_progress.show();
    }
    /**
     * 判断布局类型
     */
    private void isType(){

        if (TAGTYPE.equals("账号密码登录")){
            Titles.initTitle(mView,"账号密码登录");
            login_normal= (LinearLayout) findViewById(R.id.login_normal);
            login_duanxin= (LinearLayout) findViewById(R.id.login_duanxin);
            login_normal.setVisibility(View.VISIBLE);
            login_duanxin.setVisibility(View.INVISIBLE);
            login_phonenormal= (EditText) findViewById(R.id.login_phonenormal);
            login_psdnormal= (EditText) findViewById(R.id.login_psdnormal);
            btn_enrollnormal= (Button) findViewById(R.id.btn_enrollnormal);
            login_type= (TextView) findViewById(R.id.login_type);
            btn_enrollnormal.setOnClickListener(this);
            login_type.setOnClickListener(this);
        }
        else if (TAGTYPE.equals("短信验证")){
            Titles.initTitle(mView,"手机验证码登录");
            login_duanxin= (LinearLayout) findViewById(R.id.login_duanxin);
            login_normal= (LinearLayout) findViewById(R.id.login_normal);
            login_normal.setVisibility(View.INVISIBLE);
            login_duanxin.setVisibility(View.VISIBLE);
            login_phone= (EditText) findViewById(R.id.login_phone);
            login_psd= (EditText) findViewById(R.id.login_psd);
            btn_enroll= (Button) findViewById(R.id.btn_enroll);
            login_type= (TextView) findViewById(R.id.login_type);
            login_send= (Button) findViewById(R.id.login_send);
            login_typeduanxin= (TextView) findViewById(R.id.login_typeduanxin);
            login_typeduanxin.setOnClickListener(this);
            login_send.setOnClickListener(this);
            btn_enroll.setOnClickListener(this);
        }
    }

    private String phone,psd;
    private Map<Object,Object>map;
    @Override
    public void onClick(View view) {
        int id=view.getId();
        switch (id){
            //无验证登录
            case R.id.btn_enrollnormal:
                phone=login_phonenormal.getText().toString().trim();
                psd=login_psdnormal.getText().toString().trim();

                map=new HashMap<>();
                map.put("mobile",phone);
                map.put("pwd",psd);

                setRequest(MyUrl.url+MyUrl.login,map,handler,1);
                login_phonenormal.setText("");
                login_psdnormal.setText("");

                break;
            case R.id.login_type:
                TAGTYPE="短信验证";
                isType();
                break;
            //短信
            case R.id.login_typeduanxin:
                TAGTYPE="账号密码登录";
                isType();
                break;
            //验证提交
            case R.id.btn_enroll:
                phone=login_phone.getText().toString().trim();
                psd=login_psd.getText().toString().trim();
                if(!psd.equals("")){
                    map=new HashMap<>();
                    map.put("mobile",phone);
                    map.put("code",psd);
                    setRequest(MyUrl.url+MyUrl.duanxinlogin,map,handler,1);
                    login_phone.setText("");
                    login_psd.setText("");
                }else{
                    ToastUtils.toast("请输入验证码");
                }
                break;
            //发送验证码
            case R.id.login_send:

                phone=login_phone.getText().toString().trim();
                if(!phone.equals("")){
                    time.start();
                    map=new HashMap<>();
                    map.put("mobile",phone);
                    setRequest(MyUrl.url+MyUrl.member,map,handler,3);
                }else{
                    ToastUtils.toast("请输入手机号");
                }
                break;
            case R.id.login_qq://qq
                type="qq";
                Platform qq= ShareSDK.getPlatform(QQ.NAME);
                setValide(qq,"QQ");
                break;
            case R.id.login_wx://wx
                type="wechat";
                Platform wx= ShareSDK.getPlatform(Wechat.NAME);
                setValide(wx,"微信");
                break;
            case R.id.login_sina://sina
                type="weibo";
                Platform sina= ShareSDK.getPlatform(SinaWeibo.NAME);
                setValide(sina,"新浪微博");
                break;
        }
    }
    private void setValide(Platform name,String title){
        if (name.isValid()){//是否授权
            name.removeAccount(true);//取消授权

        }
        if (name.isClientValid()){//客户端是否存在

        }
        else {
            ToastUtils.toast("没有安装"+title+"客户端");
        }
        name.setPlatformActionListener(this);
        dialog=ProgressDialog.show(LoginAcitivity.this, "", "正在登陆，耐心等待......");
        dialog.setCanceledOnTouchOutside(true);
        name.showUser(null);//授权并获取用户信息
    }

    /**
     * 请求接口
     */
    private void setRequest(String url, Map<Object,Object>map,Handler handler,int tag){
        setProgress();
        OkttpUtils.getIntence().OkttpPost(url,map,handler,tag);
    }
    /**
     * handler
     */
    private String jsonString;
    private int code;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                jsonString=msg.getData().getString("result");
                JSONObject object=new JSONObject(jsonString);
                code=object.getInt("code");
                if (code==100){
                    if (msg.what==1){
                        ToastUtils.toast(object.getString("msg"));
                        JSONObject result=object.getJSONObject("result");
                        JsonLogin(result.toString());
                        String uniique=result.getString("unique");
                        String web_token=result.getString("web_token");

                        if(!web_token.equals("")){
                            SharePreceUtils.saveString("usertoken",web_token,"web_token");
                        }
                        JSONObject svip=result.getJSONObject("svip");
                        String svipState=svip.getString("state");
                        if(!svipState.equals("")){
                            SharePreceUtils.saveString("svip",svipState,"svipState");
                        }
                        int mobile=result.getInt("mobile");
                        JSONObject basic=result.getJSONObject("basic");
                        String state=basic.getString("state");
                        if (state.equals("1")){
                            JSONObject basic2=basic.getJSONObject("basic");
                            /**
                             * 保存数据
                             */
                            SharePreceUtils.saveData(basic2.getString("unique"),basic2.getString("thumb"),basic2.getString("nickname"),basic2.getString("weixinid"),
                                    basic2.getString("industry"),basic2.getString("occupation"),basic2.getString("city"),basic2.getString("company"),mobile+""
                                    ,true,basic2.getString("id"));
//                            JumpIntents.startIntent(LoginAcitivity.this,setActivity.class);
                            finish();
                        }
                        else if (state.equals("0")){

                            SharePreceUtils.saveRegiter(result.getString("unique"),mobile);
                            JumpIntents.startIntentCan(LoginAcitivity.this,PerfectMeansAcitivity.class,"完善个人资料");
                        }
                        finish();
                    }
                    else if (msg.what==3){
                        ToastUtils.toast(object.getString("msg"));
                    }
                    /**
                     * 获取第三方登录
                     */
                    else if (msg.what==4){
                        JSONObject result=object.getJSONObject("result");
                        state=result.getInt("state");
                        if (state==101){//未注册跳到注册界面
                            connect_third=result.getString("connect_third");
                            connect_uuid=result.getString("connect_uuid");
                            ToastUtils.toast("请先注册");
                            bundle=new Bundle();
                            bundle.putString("connect_third",connect_third);
                            bundle.putString("connect_uuid",connect_uuid);
                            bundle.putString("Tag","第三方");
                            JumpIntents.startIntent(LoginAcitivity.this,RegisterActivity.class,bundle);
                        }
                        else if (state==100){//登录成功
                            ToastUtils.toast("登录成功");
                            JsonLogin(result.toString());

                        }
                    }
                }
                else if(code==403){
                    ToastUtils.toast(object.getString("msg"));
                }
                if (dialog_progress.isShowing()&&dialog_progress!=null){
                    dialog_progress.dismiss();
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    };

    /**
     * 解析登录获取到的数据
     */
    private void JsonLogin(String results){

        try {

            JSONObject result=new JSONObject(results);
            String uniique=result.getString("unique");
            int mobile=result.getInt("mobile");
            JSONObject basic=result.getJSONObject("basic");
            String state=basic.getString("state");
            if (state.equals("1")){
                LogUtils.getInstence().info("新浪");
                JSONObject basic2=basic.getJSONObject("basic");
                /**
                 * 保存数据
                 */

                SharePreceUtils.saveData(basic2.getString("unique"),basic2.getString("thumb"),basic2.getString("nickname"),basic2.getString("weixinid"),
                        basic2.getString("industry"),basic2.getString("occupation"),basic2.getString("city"),basic2.getString("company"),mobile+""
                        ,true,basic2.getString("id"));
//                JumpIntents.startIntent(LoginAcitivity.this,setActivity.class);

            }
            else if (state.equals("0")){

                SharePreceUtils.saveRegiter(result.getString("unique"),mobile);
                JumpIntents.startIntentCan(LoginAcitivity.this,PerfectMeansAcitivity.class,"完善个人资料");
            }
            finish();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        SharePreceUtils.saveOne("type",1,"show");
    }
    private static final int MSG_ACTION_CCALLBACK = 2;
    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        Message msg = new Message();

        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 1;
        msg.arg2 = i;
        msg.obj = platform;
        if (platform.getName().equals(QQ.NAME)){
            UIHandler.sendMessage(msg,this);
        }
        else {
            UIHandler.sendMessage(msg, this);
        }

    }
    @Override
    public void onError(Platform platform, int i, Throwable throwable) {

        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 2;
        msg.arg2 = i;
        msg.obj = throwable;
        UIHandler.sendMessage(msg, this);
        // 分享失败的统计
        ShareSDK.logDemoEvent(4, platform);
    }
    @Override
    public void onCancel(Platform platform, int i) {

        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 3;
        msg.arg2 = i;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }
    /**
     * 第三方登录授权状态
     * @param msg
     * @return
     */
    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.arg1) {
            case 1:
                // 成功
                Toast.makeText(LoginAcitivity.this, "授权成功", Toast.LENGTH_SHORT).show();
                Platform platform=(Platform)msg.obj;
                uuid=platform.getDb().getUserId();
                SharePreceUtils.saveLoginUUid(uuid,type);
                Map<Object,Object>map=new HashMap<>();
//                if(MyTools.isOpenNet(LoginAcitivity.this).equals(MyTools.NOTNET)){
//                    Toast.makeText(LoginAcitivity.this,"网络异常", Toast.LENGTH_SHORT).show();
//                }
//                else {

                map.put("third", SharePreceUtils.getOther("loginUuid","typed"));
                map.put("uuid", SharePreceUtils.getOther("loginUuid","userid"));
//                LogUtils.getInstence().info();
                setRequest(MyUrl.LOGINURL,map,handler,4);//请求接口
//                }
                if(dialog!=null){
                    dialog.dismiss();
                }
                break;
            case 2:
                // 失败
                if(dialog!=null){
                    dialog.dismiss();
                }
                Throwable throwable=(Throwable)msg.obj;
                Toast.makeText(LoginAcitivity.this, "授权失败", Toast.LENGTH_SHORT).show();
                break;
            case 3:
                // 取消
                if(dialog!=null){
                    dialog.dismiss();
                }
                Toast.makeText(LoginAcitivity.this, "取消授权", Toast.LENGTH_SHORT).show();
                break;
        }
        return false;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShareSDK.stopSDK(this);

    }

    /**
     * 设置时间
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);

        }
        @Override
        public void onTick(long l) {
            login_send.setClickable(false);
            login_send.setBackgroundResource(R.drawable.login_yanzm_button_select_back_false);
            login_send.setText("等待"+l/1000+"秒");
        }
        @Override
        public void onFinish() {
            login_send.setText("重新获取");
            login_send.setBackgroundResource(R.drawable.login_yanzm_button_back);
            login_send.setClickable(true);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (dialog!=null){
            dialog.dismiss();
        }
        if (dialog_progress!=null&&dialog_progress.isShowing()){
            dialog_progress.dismiss();
        }
    }
}
